/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Servlet;

import Controllers.GestoreAnnunci;
import SBforEntityClasses.AnnuncioFacade;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//per il captcha
import net.tanesha.recaptcha.ReCaptchaImpl;
import net.tanesha.recaptcha.ReCaptchaResponse;

/**
 *
 * @author ale
 */
public class Controller extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

        /*codice per provare la jsp di registrazione*/
        String par = request.getParameter("action");
        if (par.equals("mostraRegistrazioneUtenteSito")) {

            RequestDispatcher rd = getServletContext().getRequestDispatcher("/registrazioneUtenteSito.jsp");
            rd.forward(request, response);
        } /*codice di prova *solo* per vedere se funziona il captcha */ else if (request.getParameter("action").equals("registraUtenteSito")) {
            PrintWriter out = response.getWriter();
            try {
                //TODO output your page here
                out.println("<html>");
                out.println("<head>");
                out.println("<title>Prova captcha</title>");
                out.println("</head>");
                out.println("<body>");
                out.println("<h1>Servlet Controller at " + request.getContextPath() + "</h1>");

                //codice captcha
                String remoteAddr = request.getRemoteAddr();
                ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
                reCaptcha.setPrivateKey("6LefcscSAAAAACNpi1dCi4RQn14Vwh3syoAWTLAS");

                String challenge = request.getParameter("recaptcha_challenge_field");
                String uresponse = request.getParameter("recaptcha_response_field");
                ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAddr, challenge, uresponse);

                if (reCaptchaResponse.isValid()) {
                    out.print("Answer was entered correctly!");
                } else {
                    out.print("Answer is wrong");
                }
                //fine codice captcha

                out.println("</body>");
                out.println("</html>");

            } finally {
                out.close();
            }
        } else  if (request.getParameter("action").equals("inserisciAnnuncio")) {
            
            PrintWriter out = response.getWriter();

            try {
                // TODO output your page here
                out.println("<html>");
                out.println("<head>");
                out.println("<title>Servlet VistaInserimentoAnnuncio</title>");
                out.println("</head>");
                out.println("<body>");
                out.println("<h1>Servlet VistaInserimentoAnnuncio at " + request.getContextPath() + "</h1>");
                //controllo dell'input
                boolean error = false;
                Enumeration<String> pN = request.getParameterNames();
                while (pN.hasMoreElements()) {
                    String n = pN.nextElement();
                    String s = request.getParameter(n);
                    error |= s.equals("");
                }
                DateFormat dataP = new SimpleDateFormat("dd-MM-yyyy");
                Date dataOrdine = null, dataChiusura = null;
                if (!error) {
                    dataOrdine = dataP.parse(request.getParameter("ordine"));
                    dataChiusura = dataP.parse(request.getParameter("chiusura"));
                    error |= dataOrdine.before(dataChiusura);
                }
                if (error) {
                    out.println("O hai dimenticato un campo o hai sbagliato le date");
                    //bottone: ripeti
                } else {
                    out.println("Fin qui tutto bene");           
                    
                    //(sito, chiusura, ordine, spedizione, gratuita, minimaGratuita, spesaIniziale);
                    out.println("O");
                    GestoreAnnunci ga = new GestoreAnnunci();
                    out.println("fin Qui bene");
                    ga.inserisciAnnuncio(new URL(request.getParameter("url")), dataOrdine, dataChiusura, Double.valueOf(request.getParameter("speseSped")), true, Double.valueOf(request.getParameter("spesaMinima")), Double.valueOf(request.getParameter("spesaCreatore")));
//                    out.println("Numero annunci: " + new AnnuncioFacade().numeroAnnunci());
                }
                out.println("</body>");
                out.println("</html>");

            } catch (ParseException ex) {
                out.println(Thread.currentThread().getStackTrace());
                Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex) ;
            } finally {
                out.close();
            }
        }


    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
